<?php
namespace app\controller\api;

use app\model\api\fire\FireAuthor;
use app\model\api\fire\FireLike;
use app\model\api\fire\FireRecord;
use app\model\api\fire\FireCollect;
use laytp\controller\Api;
use laytp\traits\JsonReturn;
use think\exception\ValidateException;
use think\facade\Db;
/**
 * Class Fire
 * @package app\controller\api
 */
class Fire extends Api
{
    use JsonReturn;

    protected $noNeedLogin = [];
    protected $fireAuthorModel;
    protected $fireRecordModel;
    protected $fireCollectModel;
    protected $fireLikeModel;


    protected function _initialize()
    {
        $this->fireAuthorModel  = new FireAuthor();
        $this->fireRecordModel  = new FireRecord();
        $this->fireCollectModel = new FireCollect();
        $this->fireLikeModel    = new FireLike();
    }


    /**
     * 键位/灵敏度发布记录
     */
    public function record()
    {
        $data = input('post.');
        $page = !empty($data['page'])?$data['page']:1;
        $limit = !empty($data['limit'])?$data['limit']:10;
        $device = !empty($data['device'])?$data['device']:'';
        $finger = !empty($data['finger'])?$data['finger']:'';
        $author = !empty($data['author'])?$data['author']:'';
        $openid = !empty($data['openid'])?$data['openid']:'';
        $is_home = !empty($data['is_home'])?$data['is_home']:0;

        try{
            //验证器
            validate(\app\validate\api\Fire::class)
                ->scene('list')
                ->check([
                    'page' => $page,
                    'limit' => $limit,
                ]);

            $return_data = array();
            $where = array('status' => 1);
            if(!empty($device)){
                $where['device'] = $device;
            }
            if(!empty($finger)){
                $where['finger'] = $finger;
            }
            if(!empty($author)){
                $where['author_id'] = $author;
            }
            if($is_home){
                $where['type'] = 2;
            }

            $author_info = $this->fireAuthorModel->getAuthor();
            $list = $this->fireRecordModel
                ->where($where)->order('author_sort desc,sort desc,type desc')->page($page,$limit)->select()->toArray();
            $collect_ids = $this->fireCollectModel->getCollect($openid);
            $like_ids = $this->fireLikeModel->getLike($openid);
            foreach($list as $item){
                $is_collect = 0;
                $is_like = 0;
                if(in_array($item['id'],$collect_ids)){
                    $is_collect = 1;
                }
                if(in_array($item['id'],$like_ids)){
                    $is_like = 1;
                }

                $return_data[] = array(
                    'record_id' => $item['id'],
                    'like_num' => $item['like_num'],
                    'type' => $item['type'],
                    'author_id' => $item['author_id'],
                    'author_head' => $author_info[$item['author_id']]['author_head'],
                    'author_name' => $author_info[$item['author_id']]['author_name'],
                    'author_type' => $author_info[$item['author_id']]['role_type'],
                    'icon'   => $author_info[$item['author_id']]['icon'],
                    'hand' => !empty($item['hand'])?json_decode($item['hand'],true):[],
                    'code'   => $item['code'],
                    'img'    => !empty($item['img'])?$item['img']:'',
                    'device' => $item['device'],
                    'finger' => $item['finger'],
                    'is_collect'  => $is_collect,
                    'is_like'     => $is_like,
                    'create_time' => $item['create_time'],
                    'gyroscope_remark' => $item['gyroscope_remark'],
                    'mirror_remark' => $item['mirror_remark'],
                );
            }

            return $this->success('success',$return_data);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }


    /**
     * 获取发布记录详情
     */
    public function recordInfo()
    {
        $data = input('post.');
        $record_id = !empty($data['record_id'])?$data['record_id']:"";

        try{
            //验证器
            validate(\app\validate\api\Fire::class)
                ->scene('detail')
                ->check([
                    'record_id' => $record_id
                ]);

            //查询发布记录
            $author_info = $this->fireAuthorModel->getAuthor();
            $info = FireRecord::find($record_id);
            $detail = array(
                'record_id' => $info->id,
                'author_head' => $author_info[$info->author_id]['author_head'],
                'author_name' => $author_info[$info->author_id]['author_name'],
                'author_type' => $author_info[$info->author_id]['role_type'],
                'icon'        => $author_info[$info->author_id]['icon'],
                'device'      => $info->device,
                'finger'      => $info->finger,
                'code'        => $info->code,
                'img'         => !empty($info->img)?$info->img:'',
                'hand'        => !empty($info->hand)?json_decode($info->hand,true):[],
                'gyroscope'   => !empty($info->gyroscope)?json_decode($info->gyroscope,true):[],
                'create_time' => $info->create_time,
                'gyroscope_remark' => $info->gyroscope_remark,
                'mirror_remark' => $info->mirror_remark,
            );

            return $this->success('success',$detail);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }

    }

    /**
     * 收藏/取消收藏
     */
    public function like(){
        $data = input('post.');
        $openid = !empty($data['openid'])?$data['openid']:'';
        $record_id = !empty($data['record_id'])?$data['record_id']:'';

        try{
            //验证器
            validate(\app\validate\api\Fire::class)
                ->scene('like')
                ->check([
                    'record_id' => $record_id,
                    'openid' => $openid
                ]);

            $like_ids = $this->fireLikeModel->getLike($openid);

            try{
                Db::startTrans();
                if(in_array($record_id,$like_ids)){
                    $res = $this->fireLikeModel->where(array('record_id' => $record_id))->delete();
                    $like_res = $this->fireRecordModel->where(array('id' => $record_id))
                        ->dec('like_num', 1)
                        ->update();
                }else{
                    $res = $this->fireLikeModel->save(array(
                        'openid' => $openid,
                        'record_id' => $record_id,
                        'create_time' => time(),
                    ));

                    $like_res = $this->fireRecordModel->where(array('id' => $record_id))
                        ->inc('like_num',1)
                        ->update();
                }

                if($res === false || $like_res === false){
                    Db::rollback();
                    return $this->error('点赞失败',[]);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('success',[]);

            }catch (\Exception $e){
                return $this->error($e->getMessage(),[]);
            }

        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }

    /**
     * 收藏/取消收藏
     */
    public function collect(){
        $data = input('post.');
        $openid = !empty($data['openid'])?$data['openid']:'';
        $record_id = !empty($data['record_id'])?$data['record_id']:'';

        try{
            //验证器
            validate(\app\validate\api\Fire::class)
                ->scene('collect')
                ->check([
                    'record_id' => $record_id,
                    'openid' => $openid
                ]);

            $collect_ids = $this->fireCollectModel->getCollect($openid);
            if(in_array($record_id,$collect_ids)){
                $res = $this->fireCollectModel->where(array('record_id' => $record_id))->save(array('delete_time' => time()));
            }else{
                $res = $this->fireCollectModel->save(array(
                    'openid' => $openid,
                    'record_id' => $record_id,
                ));
            }

            if($res === false){
                return $this->error('收藏失败',[]);
            }

            return $this->success('success',[]);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }

    /**
     * 我的收藏
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function collectList(){
        $data = input('post.');
        $page = !empty($data['page'])?$data['page']:1;
        $limit = !empty($data['limit'])?$data['limit']:10;
        $openid = !empty($data['openid'])?$data['openid']:'';
        $type = !empty($data['type'])?$data['type']:'';

        try{
            //验证器
            validate(\app\validate\api\Fire::class)
                ->scene('collect_list')
                ->check([
                    'page' => $page,
                    'limit' => $limit,
                    'openid' => $openid
                ]);

            $return_data = array();
            $collect_ids = $this->fireCollectModel->getCollect($openid);

            $where = [];
            if(!empty($type)){
                $where['type'] = $type;
            }

            $author_info = $this->fireAuthorModel->getAuthor();
            $list = $this->fireRecordModel->where($where)->order('sort desc')
                ->select($collect_ids)->toArray();
            foreach($list as $item){
                $return_data[] = array(
                    'record_id' => $item['id'],
                    'img' => $item['img'],
                    'type' => $item['type'],
                    'author_id' => $item['author_id'],
                    'author_head' => $author_info[$item['author_id']]['author_head'],
                    'author_name' => $author_info[$item['author_id']]['author_name'],
                    'author_type' => $author_info[$item['author_id']]['role_type'],
                    'icon'        => $author_info[$item['author_id']]['icon'],
                    'hand'        => !empty($item['hand'])?json_decode($item['hand'],true):[],
                    'code'        => $item['code'],
                    'device'      => $item['device'],
                    'finger'      => $item['finger'],
                    'is_collect'  => 1,
                    'create_time' => $item['create_time'],
                    'gyroscope_remark' => $item['gyroscope_remark'],
                    'mirror_remark' => $item['mirror_remark'],
                );
            }

            return $this->success('success',array(
                'data' => $return_data,
                'total' => count($collect_ids),
            ));
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }
}
